#!/usr/bin/env python

from collections import defaultdict, Counter
import struct
import sys
import time

import numpy

OKAY = 0x6F6B6179
WHA  = 0x7768613f
RITE = 0x72697465 
READ = 0x72656164 
PING = 0x70696e67
EVNT = 0x65766e74
WAVE = 0x77617665

def parse_samples(words):
    samps = []
    mlo = 0xFFFF
    mhi = 0xFFFF0000
    print "words!", len(words)
    for w in words:
        samps.append(w & mlo)
        samps.append((w & mhi) >> 16)

    return samps

def asic_info(word):
    win = word & 0x1FF
    ch = (word & 0xe00) >> 9
    row = (word & 0x3000) >> 12
    col = (word & 0xc000) >> 14
    
    return row, col, ch, win


def main():
    with open(sys.argv[1]) as fpin:
        bytestr = fpin.read()

    if len(bytestr) % 4 != 0:
        msg = "Data length ({0} bytes) not a multiple of 4"
        raise ValueError(msg.format(len(bytestr)))

    nwords_file = len(bytestr) / 4
    words = numpy.asarray(struct.unpack(str(nwords_file) + "I", bytestr))

    print nwords_file, "words read"

    # samples[ch][win][sample #] 
    samples = []

    for ch in xrange(8):
        samples.append([])
        for win in xrange(64):
            samples[ch].append([])
            for samp in xrange(64):
                samples[ch][win].append([])


    packet_indices = numpy.where(words == 0xbe11e2)[0]
    
    ctr = Counter()
    for j in xrange(len(packet_indices) - 1):
        start = packet_indices[j]
        stop  = packet_indices[j+1]

        packet = words[start:stop]

        ctr[hex(packet[2])] += 1

        if packet[2] != WAVE:
            continue

        row, col, ch, win = asic_info(packet[6])
        
        samples = parse_segments(packet[8:])
            
        for i, samp in enumerate(samples):
            samples[ch][win][i].append(samp)

    data = numpy.asarray(samples)
    
    print data.shape
        
    print ctr.most_common(10)



if __name__ == "__main__":
    sys.exit(main())
